package com.example.demo.listener;

import com.example.demo.Entity.User;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.ServletContext;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@WebListener
public class OnlineUsersListener implements HttpSessionAttributeListener {

    @Override
    public void attributeAdded(HttpSessionBindingEvent event) {
        // 只处理USER属性的添加
        if (!"user".equals(event.getName())) {
            return;
        }

        Object userObj = event.getValue();
        if (!(userObj instanceof User)) {
            return;
        }
        User loginUser = (User) userObj;

        ServletContext application = event.getSession().getServletContext();

        synchronized (application) {
            // 使用ConcurrentHashMap保证线程安全
            Map<Integer, User> onlineUsers = (ConcurrentHashMap<Integer, User>)
                application.getAttribute("ONLINE_USER");

            if (onlineUsers == null) {
                onlineUsers = new ConcurrentHashMap<>();
            }

            // 以用户ID为键存储用户对象
            if (!onlineUsers.containsKey(loginUser.getUserId())) {
                onlineUsers.put(loginUser.getUserId(), loginUser);
                application.setAttribute("ONLINE_USER", onlineUsers);
            }
        }
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent event) {
        // 处理USER属性的移除（用户登出）
        if ("USER".equals(event.getName())) {
            Object userObj = event.getValue();
            if (userObj instanceof User) {
                User logoutUser = (User) userObj;
                ServletContext application = event.getSession().getServletContext();

                synchronized (application) {
                    Map<Integer, User> onlineUsers = (ConcurrentHashMap<Integer, User>)
                        application.getAttribute("ONLINE_USER");

                    if (onlineUsers != null) {
                        onlineUsers.remove(logoutUser.getUserId());
                        application.setAttribute("ONLINE_USER", onlineUsers);
                    }
                }
            }
        }
    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent event) {
        // 会话属性替换时的处理（根据需求可不实现）
    }
}
